package com.rmiad.config;

import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Init;
import org.noear.solon.flow.stateful.StatefulFlowEngine;
import org.noear.solon.flow.stateful.controller.BlockStateController;
import org.noear.solon.flow.stateful.driver.StatefulSimpleFlowDriver;
import org.noear.solon.flow.stateful.repository.InMemoryStateRepository;
import org.noear.solon.hotplug.PluginManager;

import java.io.File;

/**
 * @author wyl
 * @date 2025年05月03日 上午11:40
 */
@Slf4j
@Configuration
public class GlobalConfig {

    @Init
    public void init() {
        Solon.app().get("sys/config", ctx -> {
            ctx.render(ONode.newObject().set("status", 0)
                    .set("data", ONode.newObject().set("systemName", Solon.cfg().get("solon.app.systemName", "插件管理系统")))
            );
        });

        File[] files = Utils.getFile("./plugins").listFiles();
        if (files == null || files.length == 0) {
            log.info("插件目录为空");
            return;
        }

        for (File file : files) {
            // 4. 过滤 JAR 文件
            if (file.isFile() && file.getName().endsWith(".jar")) {
                // 新增插件
                String fileName = file.getName();
                PluginManager.add(fileName.substring(0, fileName.lastIndexOf('-')), file);
                PluginManager.start(fileName.substring(0, fileName.lastIndexOf('-')));
            }
        }
    }

    @Bean
    public StatefulFlowEngine statefulFlowEngine() {
        return StatefulFlowEngine.newInstance(StatefulSimpleFlowDriver.builder()
                .stateController(new BlockStateController())
                .stateRepository(new InMemoryStateRepository()) //状态仓库（支持持久化）
                .build());
    }

}
